<template>
  <view class="my-collections-container">
    <!-- 页头 -->
    <CustomHeader></CustomHeader>
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">我的收藏</text>
        <view class="header-right"></view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-section">
      <!-- 空状态 -->
      <view v-if="jobList.length === 0 && !loading" class="empty-state">
        <image
          src="/static/images/candidate/empty.png"
          class="empty-image"
        ></image>
        <text class="empty-text">暂时没有收藏的职位~</text>
      </view>

      <!-- 职位列表 -->
      <scroll-view
        v-else
        class="job-list"
        scroll-y
        @scrolltolower="onScrollToLower"
        lower-threshold="50"
        :style="{ height: scrollHeight + 'px' }"
      >
        <view class="job-list-content">
          <!-- 加载中提示 -->
          <view v-if="loading && jobList.length === 0" class="loading-state">
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 职位列表项 -->
          <view
            v-for="job in jobList"
            :key="job.jobId"
            class="job-item"
            @click="goToJobDetail(job.jobId)"
          >
            <view class="job-header">
              <text class="job-name">{{ job.jobName }}</text>
              <text class="job-salary">{{ formatSalary(job) }}</text>
            </view>

            <!-- 企业信息 -->
            <view class="company-info">
              <text class="company-name">{{
                job.companyName
              }}</text>
              <text class="separator">·</text>
              <text class="company-detail">{{
                job.financStage
              }}</text>
              <text class="separator">·</text>
              <text class="company-detail">{{
                formatPeopleSize(job.peopleSize)
              }}</text>
            </view>

            <!-- 岗位性质 -->
            <view class="job-nature">
              <text class="nature-tag" v-if="job.edu">{{ job.edu }}</text>
              <text class="nature-tag" v-if="job.expYears">{{
                job.expYears
              }}</text>
              <text class="nature-tag" v-if="job.monthlySalary"
                >{{ job.monthlySalary }}薪</text
              >
            </view>

            <!-- 标签 -->
            <view class="job-tags" v-if="job.tags">
              <text
                class="job-tag"
                v-for="tag in getTopTags(job.tags, 5)"
                :key="tag"
                >{{ tag }}</text
              >
            </view>

            <!-- HR信息和地址 -->
            <view class="job-footer">
              <view class="hr-info">
                <image
                  :src="job.face || '/static/images/avatar.png'"
                  class="hr-avatar"
                ></image>
                <view class="hr-text">
                  <text class="hr-name">{{ job.name || "HR" }}</text>
                  <text class="hr-position"
                    >· {{ job.position || "" }}</text
                  >
                </view>
              </view>
              <text class="job-city">{{ job.city }}</text>
            </view>
          </view>

          <!-- 加载更多 -->
          <view v-if="loadingMore" class="load-more">
            <text class="load-more-text">加载中...</text>
          </view>

          <!-- 没有更多数据 -->
          <view v-else-if="!hasMore && jobList.length > 0" class="no-more">
            <text class="no-more-text">已经到底了</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import CustomHeader from "@/components/CustomHeader.vue";
import { getCollectedJobListApi } from "@/api/position.js";
import { getDictionary } from "@/api/resume.js";
import { companySizeCacheManager } from "@/utils/cache.js";

// 响应式数据
const scrollHeight = ref(500);
const jobList = ref([]); // 职位列表

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loading = ref(false);
const loadingMore = ref(false);

// 页面加载
onMounted(() => {
  nextTick(() => {
    calculateScrollHeight();
    // 获取公司规模数据
    loadCompanySizeData();
    // 初始化加载职位列表
    loadJobList(true);
  });
});

// 计算滚动区域高度
const calculateScrollHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    console.log("系统信息:", systemInfo);

    // 计算可用高度：总高度 - 页头高度 - 安全区域
    const headerHeight = uni.upx2px(128); // 页头高度

    // 添加安全区域底部高度
    const safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0;

    let availableHeight =
      systemInfo.windowHeight -
      headerHeight -
      safeAreaBottom;

    // 确保最小高度
    availableHeight = Math.max(availableHeight, 300);

    scrollHeight.value = availableHeight;
    console.log(
      "计算的scroll-view高度:",
      scrollHeight.value,
      "原始窗口高度:",
      systemInfo.windowHeight
    );
  } catch (error) {
    console.error("计算滚动高度失败:", error);
    // 设置一个默认高度
    scrollHeight.value = 500;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 加载收藏的职位列表
const loadJobList = async (isRefresh = false) => {
  console.log(
    "获取收藏职位列表 - isRefresh:",
    isRefresh,
    "currentPage:",
    currentPage.value
  );

  if (loading.value && !isRefresh) {
    console.log("正在加载中，跳过");
    return;
  }
  if (loadingMore.value && isRefresh) {
    console.log("正在加载更多，跳过刷新");
    return;
  }

  try {
    if (isRefresh) {
      currentPage.value = 1;
      loading.value = true;
      jobList.value = []; // 清空列表
      console.log("刷新模式 - 清空列表，重置页码");
    } else {
      if (!hasMore.value) {
        console.log("无更多数据可加载");
        return;
      }
      loadingMore.value = true;
      console.log("加载更多模式 - 页码:", currentPage.value);
    }

    // 构造请求参数
    const params = {
      pageNo: isRefresh ? 1 : currentPage.value,
      pageSize: pageSize.value,
    };

    console.log("请求参数:", params);

    const res = await getCollectedJobListApi(params);
    console.log("收藏职位列表响应:", res);

    if (res) {
      // 更新分页信息
      const totalPages = res.totalPages || 0;

      if (isRefresh) {
        jobList.value = res.list || [];
        currentPage.value = 1;
        console.log("刷新完成 - 当前列表长度:", jobList.value.length);
      } else {
        jobList.value.push(...(res.list || []));
        console.log("加载更多完成 - 当前列表长度:", jobList.value.length);
      }

      // 判断是否还有更多数据
      hasMore.value = currentPage.value < totalPages;
      console.log(
        "分页状态 - hasMore:",
        hasMore.value,
        "currentPage:",
        currentPage.value,
        "totalPages:",
        totalPages
      );
    }
  } catch (error) {
    console.error("获取收藏职位列表失败:", error);
    uni.showToast({
      title: "获取收藏列表失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    loadingMore.value = false;
    console.log(
      "请求结束 - loading:",
      loading.value,
      "loadingMore:",
      loadingMore.value
    );
  }
};

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log(
    "滚动到底部 - 触发加载更多 - currentPage:",
    currentPage.value,
    "hasMore:",
    hasMore.value,
    "loadingMore:",
    loadingMore.value
  );

  if (loadingMore.value || !hasMore.value) {
    console.log("已在加载中或无更多数据");
    return;
  }

  const nextPage = currentPage.value + 1;
  currentPage.value = nextPage;
  loadJobList(false);
};

// 格式化薪资显示
const formatSalary = (job) => {
  if (job.beginSalary && job.endSalary) {
    let salaryText = `${job.beginSalary}-${job.endSalary}K`;
    if (job.monthlySalary && job.monthlySalary > 0) {
      salaryText += `·${job.monthlySalary}薪`;
    }
    return salaryText;
  }
  return "面议";
};

// 获取前N个标签
const getTopTags = (tags, count) => {
  if (!tags) return [];
  const tagArray = tags.split(",");
  return tagArray.slice(0, count);
};

// 格式化公司规模
const formatPeopleSize = (peopleSize) => {
  if (!peopleSize) return "";

  // 首先尝试从缓存中获取
  const cachedValue = companySizeCacheManager.getValueByDataKey(peopleSize);
  if (cachedValue !== peopleSize) {
    return cachedValue;
  }

  // 如果缓存中没有，则使用硬编码的映射（作为后备方案）
  const sizeMap = {
    counts0_50: "0-50人",
    counts50_100: "50-100人",
    counts100_500: "100-500人",
    counts500_999: "500-999人",
    counts1000_9999: "1000-9999人",
    counts10000: "10000人以上",
  };

  return sizeMap[peopleSize] || peopleSize;
};

// 获取公司规模数据
const loadCompanySizeData = async () => {
  try {
    // 检查缓存中是否有数据
    const cachedData = companySizeCacheManager.getData();
    if (cachedData) {
      console.log("使用缓存的公司规模数据");
      return;
    }

    // 从接口获取数据
    const res = await getDictionary("staff_size");
    console.log("获取到公司规模数据:", res);

    if (res && Array.isArray(res)) {
      // 保存到缓存
      companySizeCacheManager.setData(res);
    }
  } catch (error) {
    console.error("获取公司规模数据失败:", error);
  }
};

// 跳转到职位详情
const goToJobDetail = (jobId) => {
  console.log("跳转到职位详情，jobId:", jobId);
  uni.navigateTo({
    url: `/pages/candidate/position/positionDetail?jobId=${jobId}`,
  });
};
</script>

<style lang="less" scoped>
.my-collections-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header-right {
  width: 60rpx;
}

/* 内容区域 */
.content-section {
  flex: 1;
  background-color: #f8f8f8;
  overflow: hidden;
  position: relative;
}

/* 职位列表 */
.job-list {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  /* 隐藏滚动条 */
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
    background: transparent !important;
  }

  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE 10+ */
}

.job-list-content {
  padding: 20rpx;
}

.job-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.job-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  flex: 1;
  margin-right: 20rpx;
}

.job-salary {
  font-size: 30rpx;
  font-weight: 600;
  color: #00bdb4;
}

.company-info {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.company-name {
  font-size: 26rpx;
  color: #666666;
  margin-right: 8rpx;
}

.separator {
  font-size: 26rpx;
  color: #999999;
  margin: 0 8rpx;
}

.company-detail {
  font-size: 26rpx;
  color: #999999;
}

.job-nature {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.nature-tag {
  font-size: 24rpx;
  color: #666666;
  background-color: #f5f5f5;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.job-tag {
  font-size: 24rpx;
  color: #999999;
  background-color: #f5f5f5;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.job-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hr-info {
  display: flex;
  align-items: center;
}

.hr-avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}

.hr-text {
  display: flex;
  align-items: center;
}

.hr-name {
  font-size: 26rpx;
  color: #999999;
}

.hr-position {
  font-size: 26rpx;
  color: #999999;
  margin-left: 4rpx;
}

.job-city {
  font-size: 26rpx;
  color: #999999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 100rpx 0;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* 加载状态 */
.loading-state,
.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
}

.loading-text,
.load-more-text,
.no-more-text {
  font-size: 28rpx;
  color: #999999;
}
</style>
